<template>
  <div>

    <el-dialog v-model="iconLista.dialogVisible" title="修改图标" top="1vh" width="50%" lock-scroll
      :before-close="handleaClose">
      <div class="icons">
        <div v-for="(name, index) in iconList.icons" :index="index" :key="index" class="icon" @click="chooseicon(name)">
          <component :is="icondeal(name)"></component>
          <span>{{ name }}</span>
        </div>
      </div>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="iconList.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleOk">确定</el-button>
        </span>
      </template> -->
    </el-dialog>
    <el-dialog v-model="iconList.dialogVisible" :title="zdialogStatus[dialogStatus]" top="1vh" width="50%" lock-scroll
      :before-close="handleClose">
      <div v-show="dialogStatus == 0">
        <el-form @keyup.enter="handleOk" :model="createmenues" ref="ruleFormRef" :rules="rules" label-width="80px"
          label-position="left" scroll-to-error>
          <el-form-item label="菜单名称" prop="name">
            <el-input autofocus v-model="createmenues.name" />
          </el-form-item>
          <el-form-item label="菜单路径" prop="path">
            <el-input v-model="createmenues.path" />
          </el-form-item>
          <el-form-item label="菜单描述" prop="desc">
            <el-input placeholder="只有嵌套父级路由无需填写(填写内容为components下创建的.vue文件名)" v-model="createmenues.desc" />
          </el-form-item>
          <el-form-item label="上级菜单">
            <el-tree-select v-model="createmenues.parentId" :data="sjcd" value-key="_id" check-strictly show-checkbox
              :render-after-expand="false" />
          </el-form-item>
          <el-form-item label="图标名称">
            <el-input v-model="createmenues.icon" @click="iconLista.dialogVisible = true" />
          </el-form-item>
          <el-form-item label="是否隐藏">
            <el-radio-group v-model="createmenues.hidden">
              <el-radio :label="true" size="large">是</el-radio>
              <el-radio :label="false" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model.number="createmenues.order" />
          </el-form-item>
        </el-form>
      </div>
      <div v-show="dialogStatus == 1" class="icons">
        <div v-for="(name, index) in iconList.icons" :index="index" :key="index" class="icon" @click="chooseicon(name)">
          <component :is="icondeal(name)"></component>
          <span>{{ name }}</span>
        </div>
      </div>
      <div v-show="dialogStatus == 2">
        <el-form @keyup.enter="handleOk" :model="modifyfrom" ref="ruleFormRefm" :rules="mrules" label-width="80px"
          label-position="left" scroll-to-error>
          <el-form-item label="菜单名称" prop="name">
            <el-input autofocus v-model="modifyfrom.name" />
          </el-form-item>
          <el-form-item label="菜单路径" prop="path">
            <el-input v-model="modifyfrom.path" />
          </el-form-item>
          <el-form-item v-show="!modifyfrom.hasChildren" label="菜单描述" prop="desc">
            <el-input placeholder="只有嵌套父级路由无需填写(填写内容为components下创建的.vue文件名)" v-model="modifyfrom.desc" />
          </el-form-item>
          <el-form-item label="上级菜单">
            <el-tree-select v-model="modifyfrom.parentId" :data="sjcd" value-key="_id" @change="schange" check-strictly
              show-checkbox :render-after-expand="false" />
          </el-form-item>
          <el-form-item label="图标名称">
            <el-input v-model="modifyfrom.icon" @click="iconLista.dialogVisible = true" />
          </el-form-item>
          <el-form-item label="是否隐藏">
            <el-radio-group v-model="modifyfrom.hidden">
              <el-radio :label="true" size="large">是</el-radio>
              <el-radio :label="false" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model.number="modifyfrom.order" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="iconList.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleOk">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>菜单列表</span>
          <el-button class="button" @click="addmenues" color="purple">添加菜单</el-button>
        </div>
      </template>
      <el-scrollbar height="620px">
        <el-table :data="menuesList" style="width: 100%" row-key="_id" border height="620px">
          <el-table-column align="center" :show-overflow-tooltip="true" prop="name" label="菜单名称" />
          <el-table-column align="center" :show-overflow-tooltip="true" prop="path" label="菜单路径" />
          <el-table-column align="center" :show-overflow-tooltip="true" prop="hidden" label="是否隐藏">
            <template #default="scope">
              <span>{{ scope.row.hidden ? "隐藏" : "显示" }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="level"
            label="路由层级"
          /> -->
          <el-table-column align="center" :show-overflow-tooltip="true" prop="desc" label="路由组件" />
          <el-table-column width="200" align="center" :show-overflow-tooltip="true" prop="_id" label="路由ID" />
          <el-table-column align="center" width="200" :show-overflow-tooltip="true" prop="parentId" label="父节点ID" />
          <el-table-column align="center" :show-overflow-tooltip="true" prop="order" label="排序" />
          <el-table-column align="center" :show-overflow-tooltip="true" prop="icon" label="图标" />
          <el-table-column width="200" align="center" fixed="right" label="操作">
            <template #default="scope">
              <el-button @click="modify(scope.row)" type="primary">修改</el-button>
              <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" icon="InfoFilled"
                icon-color="#626AEF" @confirm="delitem(scope.row._id)" title="确定删除此路由?">
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-card>
    <el-pagination :page-sizes="[10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script setup lang="ts">
import { getMenus, creataMenus, delMenus, putMenus } from "@/api/menus"
import * as ElIcons from "@element-plus/icons-vue"
import type { FormInstance, FormRules } from "element-plus"
import { getMenusRote } from "@/api/menus"
import storage from "@/utils/storage"
// const loading = ref(false)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  init(pageNumber.value, pageSize.value)
}
const delitem = (val: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0)",
  })
  delMenus("/bem/menus/delMenues", {
    ids: val,
  })
    .then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("路由删除成功，重新登录后生效")
        init()
      }
    })
    .catch((err: any) => {
      console.log("====================================")
      console.log(err)
      console.log("====================================")
    })
    .finally(() => {
      loading.close()
    })
}
const sjcd = ref<any[]>([])
const chooseicon = (val: string) => {
  if (dialogStatus.value == 0) {
    createmenues.icon = val
    iconLista.dialogVisible = false
  } else if (dialogStatus.value == 2) {
    modifyfrom.icon = val
    iconLista.dialogVisible = false
  }
}
const schange = (val: string) => {
  createmenues.level = sjcd.value.filter((e: any) => e.id == val)[0].level + 1
}
//formruler 类型
const ruleFormRef = ref<FormInstance>()
const ruleFormRefm = ref<FormInstance>()
//formruler
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入菜单名称", trigger: ["blur"] }],
  path: [
    {
      required: true,
      message: "请输入菜单路径",
      trigger: ["blur"],
    },
  ],
})
const mrules = reactive<FormRules>({
  name: [{ required: true, message: "请输入菜单名称", trigger: ["blur"] }],
  path: [
    {
      required: true,
      message: "请输入菜单路径",
      trigger: ["blur"],
    },
  ],
})
const createmenues = reactive({
  name: "",
  path: "",
  parentId: 0,
  icon: "Plus",
  hidden: false,
  order: 0,
  level: 1,
  desc: "",
})
const total = ref(0)
// const router = useRouter()
//0 增加 1 修改 2 删除
const dialogStatus = ref(0)
const zdialogStatus = ref(["增加路由", "修改图标", "修改路由"])
const pageNumber = ref<number>(1)
const pageSize = ref<number>(10)
const menuesList = ref([])
// const iconsList = ref([])
const modifyfrom = reactive({
  name: "",
  path: "",
  parentId: 0,
  icon: "Plus",
  hidden: false,
  order: 0,
  level: 1,
  desc: "",
  id: "",
  hasChildren: false
})
const modify = (item: any) => {
  dialogStatus.value = 2;
  iconList.dialogVisible = true;
  const { name, path, parentId, icon, hidden, order, level, desc, _id } = item;
  modifyfrom.name = name;
  modifyfrom.path = path;
  modifyfrom.parentId = parentId;
  modifyfrom.icon = icon;
  modifyfrom.hidden = hidden;
  modifyfrom.order = order;
  modifyfrom.level = level
  modifyfrom.desc = desc;
  modifyfrom.id = _id;
  modifyfrom.hasChildren = item.children;

}
const addmenues = () => {
  dialogStatus.value = 0
  iconList.dialogVisible = true
}
const icondeal = computed(() => {
  return (value: string) => {
    return `el-icon-${value.toLowerCase()}`
  }
})

// const changetest = (val: any) => {
//   console.log("====================================")
//   console.log(val)
//   console.log("====================================")
// }

const getData = () => {
  let icons = []
  for (const name in ElIcons) {
    icons.push(name)
  }
  return icons
}
const iconList = reactive({
  icons: getData(),
  dialogVisible: false,
  currentIconName: "Aim",
})
const iconLista = reactive({
  icons: getData(),
  dialogVisible: false,
  currentIconName: "Aim",
})
const handleClose = () => {
  iconList.dialogVisible = false
}
const handleaClose = () => {
  iconLista.dialogVisible = false
}
// const reload = inject("reload") as any
const cb = () => {
  getMenusRote("/bem/menus/getMenuesRoutes").then((res) => {
    if (res.code == 200) {
      storage.set("allRoute", res.data)
    }
  })
  // reload()
  handleClose()
  // router.go(0)
}
const handleOk = async () => {
  if (dialogStatus.value == 0) {
    ruleFormRef.value
      ?.validate(async (valid, fields: any) => {
        if (valid) {
          const loading = ElLoading.service({
            lock: true,
            text: "Loading",
            background: "rgba(0, 0, 0, 0)",
          })
          creataMenus("/bem/menus/createMenues", createmenues)
            .then((res: any) => {
              if (res.code == 200) {
                ElMessage.success("路由添加成功，重新登录后生效，切记不要忘记在角色权限页面授权此路由")
                ruleFormRef.value?.resetFields()
                init()
              } else {
                ElMessage.error(res.msg)
              }
            })
            .catch((err) => {
              ElMessage.error(JSON.stringify(err))
            })
            .finally(() => {
              loading.close()
            })
        } else {
          ElMessage.error(fields[Object.keys(fields)[0]][0].message)
        }
      })
      .catch((err) => {
        console.log("====================================")
        console.log(err)
        console.log("====================================")
      })
      .finally(() => {
        cb()
      })
  } else if (dialogStatus.value == 2) {
    ruleFormRefm.value
      ?.validate(async (valid, fields: any) => {
        if (valid) {
          const loading = ElLoading.service({
            lock: true,
            text: "Loading",
            background: "rgba(0, 0, 0, 0)",
          })
          putMenus("/bem/menus/putMenues", modifyfrom)
            .then((res: any) => {
              if (res.code == 200) {
                ElMessage.success("路由修改成功，重新登录后生效")
                ruleFormRef.value?.resetFields()
                init()
              } else {
                ElMessage.error(res.msg)
              }
            })
            .catch((err) => {
              ElMessage.error(JSON.stringify(err))
            })
            .finally(() => {
              loading.close()
            })
        } else {
          ElMessage.error(fields[Object.keys(fields)[0]][0].message)
        }
      })
      .catch((err) => {
        console.log("====================================")
        console.log(err)
        console.log("====================================")
      })
      .finally(() => {
        cb()
      })
  }
}
const init = (pagenum: number = 1, pagesize: number = 10) => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0)",
  })
  getMenus("/bem/menus/getMenues", {
    pageSize: pagesize,
    pageNumber: pagenum,
  })
    .then((res) => {
      //   total.value = res.data.total
      menuesList.value = res.data.list
      sjcd.value = res.data.parent0
      createmenues.parentId = sjcd.value.filter((e) => e.label == "顶级菜单")[0]._id
      // let s=res.data.parent0.filter(e=>e.name)
    })
    .finally(() => {
      loading.close()
    })
}
init(pageNumber.value, pageSize.value)
const handleCurrentChange = (val: number) => {
  pageNumber.value = val
  init(pageNumber.value, pageSize.value)
}
</script>

<style lang="scss" scoped>
:deep(.el-table__body),
:deep(.el-table__header) {
  table-layout: fixed !important;
  width: 100% !important;
}

.icons {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  height: 600px;
  overflow: auto;

  .icon {
    cursor: pointer;
    width: 60px !important;
    height: 60px !important;
    margin: 30px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    span {
      margin-top: 6px;
    }

    &:hover {
      color: #c00000;
    }
  }
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 99%;
}
</style>
